<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/19
 * Time: 14:47
 */

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\model\Reservation as ReservationModel;
use qr\QRcode;
use Exception;
use think\Db;
use think\exception\PDOException;

class Reservation extends Backend
{
	protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new ReservationModel;
    }
	
	/**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
			
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('title,manager,telephone');

            $list = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);
					
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

	public function managers()
	{
		//设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('id,username,nickname');

            $list = model('Admin')
                ->where($where)
                ->where('id', '<>', 1)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
		return $this->view->fetch();
	}
	
	public function orderlist($ids = "")
	{
		//设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('id,opentitle,username');
			model('ReservationRecord')->where('pid', 'in', $ids);
			
            $list = model('ReservationRecord')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
		return $this->view->fetch();
	}
	
	public function orderdel($ids = "")
    {
       if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = model('ReservationRecord')->getPk();

            $list = model('ReservationRecord')->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
	
	public function show_qrcode($ids = null)
	{
		$this->view->assign("ids", $ids);
		return $this->view->fetch();
	}
	
	public function qrcode($ids = null)
    {
		$row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        // 保存路径
		// false 为直接输出图片
		// ./qrcode.png为把图片保存为当前目录下，名为qrcode.png
		$filename = false;
		// 像素
		$px = 700;
		// 图片尺寸
		$size = 5;
		// 范围从 0（最差质量，文件更小）到 100（最佳质量，文件最大）。默认为 IJG 默认的质量值（大约 75）。
		$quality = 0;
        $url = 'http://'.$_SERVER['HTTP_HOST']."/mobile/venreserve/details?id=".$ids;
        QRcode::png($url, $filename, $px, $size, $quality);exit();
    }
	
	public function opentimes($ids = null)
    {
		//设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
			$this->relationSearch = true;
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('id,title');
			model('ReservationDateinfo')->where('pid', 'in', $ids);
			
            $list = model('ReservationDateinfo')
				->with('reservation')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
		$this->assignconfig("ids", $ids);
		return $this->view->fetch();
    }
	
	public function opentimesadd($ids = null)
	{
		if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $result = false;
                try {
                    $result = model('ReservationDateinfo')->allowField(true)->save($params);
                } catch (Exception $e) {
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
	}
	
	public function opentimesedit($ids = null)
	{
		$row = model('ReservationDateinfo')->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
		if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $result = false;
                try {
                    $result = $row->allowField(true)->save($params);
                } catch (Exception $e) {
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
		$this->view->assign("row", $row);
        return $this->view->fetch();
	}
	
	public function opentimesdel($ids = "")
    {
       if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = model('ReservationDateinfo')->getPk();

            $list = model('ReservationDateinfo')->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
	
    /*
     * 添加场馆
     */
    public function info()
    {
        global $_W, $_GPC;
        $sql = $this->chkauth('venreserve');
		
		$sql['id'] = $id = intval($_GPC['id']);
        if ($_POST) {
            $data=[
                'title' =>trim($_GPC['title']),
                'manager' =>trim($_GPC['manager']),
				'managerid' =>trim($_GPC['managerid']),
                'telephone' =>trim($_GPC['telephone']),
				'address' =>trim($_GPC['address']),
                'opentime' =>trim($_GPC['opentime']),
                'content' =>trim($_POST['content']),
            ];

            if($_FILES['img']['name']){
                $data['img'] = uploadFile('img', 'venreserve');
            }
            if($_GPC['status']){
                $data['status'] = 1;
            }else{
                $data['status'] = 0;
            }
			
			if($id)
			{
				db('venreserve')->where($sql)->update($data);
				
				message('修改成功','/admin/venreserve/index');
			}
			else
			{
				$data['add_time'] = time();
				$data['groupaid'] = $_W['user']['groupaid'];
				$data['groupbid'] = $_W['user']['groupbid'];
				$data['groupcid'] = $_W['user']['groupcid'];
				$data['qyid'] = $_W['qyid'];
				db('venreserve')->insert($data);
				
				message('添加成功','/admin/venreserve/index');
			}
        }

		if($id){
            $info = db('venreserve')->where($sql)->find();
            $this->assign('info',$info);
        }
        return $this->fetch();
    }

    /*
     * 删除场馆
     */
    public function del($ids = "")
    {
        global $_W, $_GPC;

        $val = 0;
        $delid = intval($_GPC['delid']);
        if($delid){
            $sql = $this->chkauth('venreserve', 1, 1);
            db('venreserve')->where($sql)->delete($delid);

            $val = 1;
        }
        echo $val;

    }

    public function orderlist1()
    {
        global $_W, $_GPC;
        $sql = $this->chkauth('venreserve');

		if($_GET['keyword']){
			$sql['username|telephone'] = ['LIKE', '%'.trim($_GPC['keyword']).'%'];
		}
		
		if($_GET['dateinfo']){
			$sql['dateinfo'] = trim($_GPC['dateinfo']);
		}
		
		if($_GET['datetime']){
			$sql['datetime'] = trim($_GPC['datetime']);
		}
		
		if($_GPC['groupaid'] && !$sql['groupaid']) $sql['groupaid'] = $_GPC['groupaid'];
		if($_GPC['groupbid'] && !$sql['groupbid']) $sql['groupbid'] = $_GPC['groupbid'];
		
        $sql['pid'] = $pid = intval($_GPC['pid']);
		$sql['canceled'] = 0;
		
		$venue = db('venreserve')->where('id',$pid)->value('title');
		$this->assign('venue',$venue);
		
		//导出
		if($_GPC['export'])
		{
			header("Content-type:application/octet-stream");
			header("Accept-Ranges:bytes");
			header("Content-type:application/vnd.ms-excel");
			header("Content-Disposition:attachment;filename=".$venue."预约列表.xls");
			header("Pragma: no-cache");
			header("Expires: 0");
			
			$list = db('venreserve_record')->where($sql)->order('id desc')->select();
			
			$title = array('序号', '开放活动', '预约人', '预约人手机', '单位', '预约时间', '是否携带家属', '预约人次', '下单时间', '核销时间');
			if (!empty($title)) {
				foreach ($title as $k => $v) {
					$title[$k] = iconv("UTF-8", "GB2312", $v);
				}
				$title = implode("\t", $title);
				echo "$title\n";
			}
			
			$exportdata = array();
			foreach($list as $key=>$value)
			{
				$data = array(
					'id' => $key+1,
					'opentitle' => $value['opentitle'],
					'username' => $value['username'],
					'telephone' => $value['telephone'],
					'department' => getGroupName($value['groupaid'], $value['groupbid'], $value['groupcid']),
					'dateinfo' => $value['dateinfo'].'（'.getWeekName($value['dateinfo']).'）'.$value['datetime'],
					'family' => $value['family']==1?'是':'否',
					'usernumber' => $value['usernumber'],
					'add_time' => getDateTime($value['add_time']),
					'completed_time' => getDateTime($value['completed_time'])
				);
				$exportdata[] = $data;
			}
			
			if (!empty($exportdata)) {
				foreach ($exportdata as $key => $val) {
					foreach ($val as $ck => $cv) {
						$exportdata[$key][$ck] = iconv("UTF-8", "GB2312", $cv);
					}
					$exportdata[$key] = implode("\t", $exportdata[$key]);
				}
				echo implode("\n", $exportdata);
			}
			exit;
		}
		
        $list = db('venreserve_record')->where($sql)->order('id desc')->paginate(20, false, [
            'query' => request()->param()
        ]);
		
		$opentimes = db('venreserve_dateinfo')->distinct(true)->field('dateinfo')->where('pid',$pid)->select();
		$this->assign('opentimes',$opentimes);
		
		$groupa = db('company_group')->where('groupid=1')->select();

		if($_GPC['groupaid']){
			$where['groupid'] = $_GPC['groupaid'];
			$groupb = db('company_group')->where($where)->select();
			$this->assign('groupb', $groupb);
		}
		$groupbarr = db('company_group')->select();

		$this->assign('groupa',$groupa);
		$this->assign('groupbarr',$groupbarr);
		
        $this->assign('list',$list);
        return $this->fetch();
    }
	
	public function record_del()
    {
        global $_W, $_GPC;
        $val = 0;
        $delid = intval($_GPC['delid']);
        if($delid){
            $sql = $this->chkauth('venreserve', 1, 1);
            db('venreserve_record')->where($sql)->delete($delid);

            $val = 1;
        }
        echo $val;
    }
	
	
	
	public function dateinfo()
    {
		global $_W, $_GPC;
		$this->chkauth('venreserve');
		
		$id = intval($_GPC['id']);
		$pid = intval($_GPC['pid']);
		
        if ($_POST) {
            $data=[
                'dateinfo' =>trim($_GPC['dateinfo']),
				'title' =>trim($_GPC['title']),
				'timetype' =>intval($_GPC['timetype']),
				'week' =>intval($_GPC['week']),
				'date' =>trim($_GPC['date']),
				'peoplelimit' =>intval($_GPC['peoplelimit']),
				'content' =>trim($_POST['content']),
				'sort' =>intval($_GPC['sort']),
            ];

			if($id)
			{
				db('venreserve_dateinfo')->where('id',$id)->update($data);
				
				message('修改成功','/admin/venreserve/opentimes?pid='.$pid);
			}
			else
			{
				$data['pid'] = $pid;
				$data['qyid'] = $_W['qyid'];
				db('venreserve_dateinfo')->insert($data);
				
				message('添加成功','/admin/venreserve/opentimes?pid='.$pid);
			}
        }

		if($id){
            $dateinfo = db('venreserve_dateinfo')->where('id',$id)->find();
        }elseif($pid){
			$dateinfo['pid'] = $pid;
		}
		
		$venue = db('venreserve')->where('id',$pid)->value('title');
		$this->assign('venue',$venue);
		$this->assign('dateinfo',$dateinfo);
        return $this->fetch();
    }
	
	public function date_del()
    {
        global $_W, $_GPC;
        $val = 0;
        $delid = intval($_GPC['delid']);
        if($delid){
            $sql = $this->chkauth('venreserve', 0, 1);
            db('venreserve_dateinfo')->where($sql)->delete($delid);

            $val = 1;
        }
        echo $val;
    }

    //商户二维码
    public function shop_qrcode()
    {
        global $_W, $_GPC;
        $id = intval($_GPC['id']);
        $shopInfo = db('venreserve')->where('id',$id)->find();
        if(!$shopInfo){
            return false;
        }

        // 保存路径
		// false 为直接输出图片
		// ./qrcode.png为把图片保存为当前目录下，名为qrcode.png
		$filename = false;
		// 像素
		$px = 700;
		// 图片尺寸
		$size = 5;
		// 范围从 0（最差质量，文件更小）到 100（最佳质量，文件最大）。默认为 IJG 默认的质量值（大约 75）。
		$quality = 0;
        $url = 'http://'.$_SERVER['HTTP_HOST']."/mobile/venreserve/details?id=".$id;
        QRcode::png($url, $filename, $px, $size, $quality);exit();
    }
	
	public function receiver()
    {
		global $_W, $_GPC;
		
		$sql['qyid'] = $_W['qyid'];
		$sql['typeid'] = 1;
		$rules = 'venreserve';
		if($_GPC['keyword']){
			$info['username|realname'] = $_GPC['keyword'];
			$sql['userid'] = db('userinfo')->where($info)->value('id');
		}
		$sql['rules'] = ['LIKE', '%'.$rules.'%'];
		$list = db('auth')->where($sql)->paginate(20, false, [
			'query' => request()->param()
		])->each(function($item, $index){
			$userinfo = getUserInfo($item['userid']);
			$item['username'] = $userinfo['username'];
			$item['realname'] = $userinfo['realname'];
			$item['telephone'] = $userinfo['telephone'];
			$item['bmzw'] = $userinfo['bmzw'];
			$item['userrole'] = getRoleName($item['roleid']);
			return $item;
		});
		
		$this->assign('list',$list);
		return $this->fetch();
    }
}